package com.example.demo.gateway.endpoint;

import com.example.demo.gateway.core.api.Api;
import com.example.demo.gateway.support.ReactiveRequestContextHolder;
import com.example.demo.response.ApiResult;
import com.example.demo.utils.ReflectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @Auther: miaoguoxin
 * @Date: 2020/3/19 17:08
 * @Description:
 */
@RestController
public class GatewayTestController {
    @Autowired
    private ServerHttpRequest serverRequest;

    private String url;
    @RequestMapping("test_gateway")
    public Mono<ApiResult<String>> testGateway(){
        Mono<ServerHttpRequest> request = ReactiveRequestContextHolder.getRequest();
        System.out.println("主线程:"+Thread.currentThread());
        AtomicReference<String> bodyRef = new AtomicReference<>();
//        request.subscribe(new Consumer<ServerHttpRequest>() {
//            @Override
//            public void accept(ServerHttpRequest serverHttpRequest) {
//                System.out.println("subscribe线程:"+Thread.currentThread());
//                bodyRef.set(serverHttpRequest.getURI().getPath());
//            }
//        });
        //System.out.println(bodyRef.get());
        return  request.flatMap(serverHttpRequest -> {
            String path = serverHttpRequest.getURI().getPath();
            System.out.println("返回线程:"+Thread.currentThread());
            return Mono.just(ApiResult.error("执行降级"));
        });
    }

    @RequestMapping("/test_val")
    public ApiResult<Api> test() throws InterruptedException {
        System.out.println("主线程:"+Thread.currentThread());
        return ApiResult.success(new Api());
    }

    public static void main(String[] args) {
        System.out.println(Thread.currentThread());
        Mono.just("ffff").doOnNext(new Consumer<String>() {
            @Override
            public void accept(String s) {
                System.out.println(s+">>>>"+Thread.currentThread());
            }
        }).subscribe();
        AtomicReference<String> bodyRef = new AtomicReference<>();
        Mono.just("1244").subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) {
                bodyRef.set(s);
            }
        });
        System.out.println(bodyRef.get());
    }
}
